from fastapi import APIRouter,status
from fastapi.responses import JSONResponse

router = APIRouter()

items = [
    {"id": 1, "name": "item1"},
    {"id": 2, "name": "item2"},
    {"id": 3, "name": "item3"},
]

@router.put("/items/{item_id}")
async def update_or_insert(item_id: int,name: str | None = None):
    # 如果传入的id在列表字典中存在，则对应更新那个字典的name，否则新增一个字典
    for item in items:
        if item["id"] == item_id:
            item["name"] = name
            return item
    items.append({"id": item_id, "name": name})
    return JSONResponse(content={"message": "新增成功"}, status_code=status.HTTP_201_CREATED)
